import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/simple_entity.dart';
import 'package:wanxiang_app/pages/my/bindAccount.dart';
import 'package:wanxiang_app/pages/my/priceMy.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/widgets/money_textField.dart';
import '../../bean/login_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../utils/user_util.dart';
import '../../widgets/account_textField2.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';
import 'package:tobias/tobias.dart' ;
import '../../widgets/simple_dialog.dart';
import 'ordersBuy.dart';
class ChargeController extends GetxController{


  String price = '';
  Map payMap = {};
  bool inputEnable = false;
  String kan_id = '';
  String from_page = '';
  @override
  void onInit() {
    super.onInit();
    payMap = Get.arguments;
    inputEnable = payMap['readOnly'];

    inputPrice = payMap['price'];

    if(payMap['from_page']!=null){
      from_page = payMap['from_page'];
    }
    if(payMap['kan_id']!=null){
      kan_id = payMap['kan_id'];
    }
    print('kan_id=='+kan_id.toString());
    _getInfo();
  }

  bool checked = true;
  changeCheck(){
    checked = !checked;
    update();
  }

  int clickIndex = 0;
  @override
  void onClose() {
    super.onClose();
  }
  String inputPrice = '';
  var psw = ''.obs;
  void _pay(){
    if(payMap['from']=='kanjia'){
      _PayKanjia();
    }else if(payMap['from']=='kanjiaOrder'){
      if(kan_id.isEmpty){
        _PayKanjiaOrder();
      }else{
        _PayKanjiaOrderAgain();
      }

    }else if(payMap['from']=='buyNow'){
      _buyNow2();
    }
  }

  void _PayKanjia(){
    DioManager.getInstance().post(ServiceUrl.kanPayNow,{
        "user_name":UserUtil.getUSER()?.userName,
      "buy_type": clickIndex==1?'3':'2',
        "new_price":payMap['new_price'],
        "deposit_price":inputPrice,
        "channel_id":payMap['channel_id'],
        "goods_id":payMap['goods_id'],
      "bargaining_id":payMap['bargaining_id'],
      'password':psw.value
    }, (data) async {
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
        if(bannerEntity.status==1){
          Get.off(()=>PriceMyPage());
        }
      }else{
        if(clickIndex == 0){
          Tobias tobias =  Tobias();
          var payRes = await tobias.pay(data);
          if(payRes['resultStatus'] == '9000'){
            ToastUtil.show('支付成功');
            Get.off(()=>PriceMyPage());
          }else{
            ToastUtil.show('支付取消');
          }

        }else{

          ToastUtil.show(data);
        }
      }

    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _PayKanjiaOrderAgain(){
    DioManager.getInstance().post(ServiceUrl.getBargainingBuyer,{
      "user_name":UserUtil.getUSER()?.userName,
      "bargaining_id":kan_id,
      'sell_price':payMap['new_price']
    }, (data) async {
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
        if(bannerEntity.status==200){
          Get.off(()=>PriceMyPage());
        }
      }else{
        if(clickIndex == 0){
          Tobias tobias = Tobias();
          var payRes = await tobias.pay(data);
          if(payRes['resultStatus'] == '9000'){
            ToastUtil.show('支付成功');
            Get.off(()=>PriceMyPage());
          }else{
            ToastUtil.show('支付取消');
          }
        }else{
          ToastUtil.show(data);
        }
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _PayKanjiaOrder(){
    DioManager.getInstance().post(ServiceUrl.kanPay,{
      "user_name":UserUtil.getUSER()?.userName,
      "buy_type": clickIndex==1?'3':'2',
      "new_price":payMap['new_price'],
      "deposit_price":inputPrice,
      "channel_id":payMap['channel_id'],
      "goods_id":payMap['goods_id'],
      'password':psw.value
    }, (data) async {
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
        if(bannerEntity.status==1){
          Get.off(()=>PriceMyPage());
        }
      }else{
        if(clickIndex == 0){
          Tobias tobias = Tobias();
          var payRes = await tobias.pay(data);
          if(payRes['resultStatus'] == '9000'){
            ToastUtil.show('支付成功');
            Get.off(()=>PriceMyPage());
          }else{
            ToastUtil.show('支付取消');
          }

        }else{

          ToastUtil.show(data);
        }
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _buy(){
    DioManager.getInstance().post(ServiceUrl.buy,{
      "user_name":UserUtil.getUSER()?.userName,
      "buy_type": clickIndex==1?'3':'2',
      "channel_id":payMap['channel_id'],
      "goods_id":payMap['goods_id'],
    }, (data) async {
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
      }else{
        if(clickIndex == 0){
          Tobias tobias = Tobias();
          tobias.pay(data);

        }else{

          ToastUtil.show(data);
        }
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  _buyNow2(){
    String url = ServiceUrl.buyNow;
    if(from_page=='detail'){
      url = ServiceUrl.buy;
    }
    DioManager.getInstance().post(url,{
      "channel_id":payMap['channel_id'],
      "goods_id":payMap['goods_id'],
      "user_name":UserUtil.getUSER()?.userName.toString(),
      "buy_type": clickIndex==1?'3':'2',
      'password':psw.value,
      'CompensationCode':payMap['CompensationCode']
    }, (data) async {
      print('datadatadata==='+data);
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
        if(bannerEntity.status==1){
          Get.to(()=>OrdersBuyPage(),arguments: 4,preventDuplicates:false);
        }
      }else{
        if(clickIndex == 0){
          Tobias tobias = Tobias();
          var payRes = await tobias.pay(data);
          if(payRes['resultStatus'] == '9000'){
            ToastUtil.show('支付成功');
            Get.to(()=>OrdersBuyPage(),arguments: 4,preventDuplicates:false);
          }else{
            ToastUtil.show('支付取消');
          }
        }else{
          ToastUtil.show(data);
        }
      }

    }, (error) {
      ToastUtil.show(error);
    });
  }

  bool isPsw = false;
  late BuildContext mContext;
  _getInfo() {
    DioManager.getInstance().post(ServiceUrl.myInfo,{
      "user_name":UserUtil.getUSER()?.userName
    }, (data1) async {
      LoginEntity  entity = LoginEntity.fromJson(jsonDecode(data1));
      if(entity.data.withdrawPw.isEmpty){
        isPsw = false;
      }else{
        isPsw = true;
      }
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }

}

class ChargePage extends GetView<ChargeController>  {

  late ChargeController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<ChargeController>(() => ChargeController());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<ChargeController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '支付',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }

  Widget _content(){
    return Container(
      padding: EdgeInsets.only(left: 20.w,right: 27.w),
      child: Column(
        children: [
          SizedBox(height: 24.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text('支付金额',style: TextStyle(color: Color(0xFF333333),fontSize: 15.sp),)
            ],
          )
          ,
          Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.r),
                color: Color(0xFFF9F9F9)
            ),
            height: 48.h,
            margin: EdgeInsets.only(
              top: 15.h,
            ),
            child: MoneyTextField(
              //获取返回的输入内容
              defaultText: controller.inputPrice,
              readOnly: true,
              hitText: '请输入金额',
              inputColor: 0xFFF9F9F9,
              contentStrCallBack: (content) {
                controller.inputPrice = content;
              }, key: ValueKey('money'),
            ),
          ),
          SizedBox(height: 28.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text('支付方式',style: TextStyle(color: Color(0xFF333333),fontSize: 15.sp),)
            ],
          )
          ,
          Container(
            margin: EdgeInsets.only(top: 14.h),
            padding: EdgeInsets.only(left: 20.w,right: 22.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(6.r),
              color: Color(0xFFF9F9F9)
            ),
            child: Column(
              children: [
                // _item(Constant.IMG_BASE+'icon_wx.png','微信',0),
                _item(Constant.IMG_BASE+'icon_zfb.png','支付宝',0),
                _item(Constant.IMG_BASE+'icon_balance.png','余额',1),
                SizedBox(height: 36.h,)
              ],
            ),
          ),
          _btn()

        ],
      ),
    );
  }
  Widget _item(img,name,index){
    return Container(
      margin: EdgeInsets.only(top: 23.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Image.asset(img,width: 34.w,height: 34.h,),
              SizedBox(width: 12.w,),
              Text(name,style: TextStyle(color: Color(0xFF333333),fontSize: 14.sp,fontWeight: FontWeight.bold),),
            ],
          ),
          InkWell(
            onTap: (){
             controller.clickIndex = index;
             controller.update();
            },
            child:    controller.clickIndex==index?
            Image.asset('${Constant.IMG_BASE}radio_y.png',width: 14.w,height: 14.h,)
                :
            Image.asset('${Constant.IMG_BASE}radio_n.png',width: 14.w,height: 14.h,)
          )

        ],
      ),
    );
  }

  Widget _btn(){
    return InkWell(
        onTap: (){
          _buyNow();
        },
        child:Container(
          margin: EdgeInsets.only(top: 30.h),
          height: 42.h,
          width: MediaQuery.of(context).size.width - 64.w,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              color: Color(0xFF007BE5),
              borderRadius: BorderRadius.circular(22.r)
          ),
          child: Text('确定',style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white
          ),),
        )
    );
  }

  Future<void> _buyNow() async {

    if(controller.clickIndex ==1){
      if(!controller.isPsw){
        showDialog(context: context, builder: (BuildContext context1) {
          return MySimpleDialog(callBack: (String content) {
            if(content == 'cancel'){
              Navigator.pop(context1);
            }else if(content == 'sure'){
              Get.to(BindAccountPage(),preventDuplicates:false )?.then((value) => controller._getInfo());
            }
          },
            msg: "请先设置支付密码？",
            sureText: "确定",
          );
        });
      }else{
        _showSingle();
      }

    }else{

      Tobias tobias = Tobias();
      var result = await tobias.isAliPayInstalled;
      if(result){
        controller._pay();
      }else{
        ToastUtil.show('请先安装支付宝');
      }

    }

  }

  Future<Future<int?>> _showSingle() async {
    return showModalBottomSheet<int>(
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        context: context,
        builder: (BuildContext context1) {
          return AnimatedPadding(
              padding: MediaQuery.of(context1).viewInsets, // 我们可以根据这个获取需要的padding
              duration: const Duration(milliseconds: 100),
              child:  Container(
                  height: 200.h,
                  clipBehavior: Clip.antiAlias,
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20.0),
                      topRight: Radius.circular(20.0),
                    ),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height: 15.h,),
                      Text('请输入密码',style: TextStyle(
                          fontSize: 15.sp
                      ),),
                      Container(
                          margin: EdgeInsets.all(10.w),
                          decoration: BoxDecoration(
                              border: Border.all(color: Color(0xFFE4E4E4),width: 1.w)
                          ),
                          child:
                          AccountEdit2Text(key: const ValueKey('title'),hitText: '请输入密码', contentStrCallBack: (value){
                            controller.psw.value = value;
                          })

                      ),
                      InkWell(
                          onTap: (){
                            controller._pay();
                            Navigator.pop(context1);
                          },
                          child:  Container(
                            height: 40.h,
                            margin: EdgeInsets.all(10.w),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8.r),
                                color: const Color(0xFF007BE5)
                            ),
                            child: Text('确定',style: TextStyle(
                                color: Colors.white,
                                fontSize: 13.sp
                            ),),
                          )
                      )

                    ],
                  )
              )
          ) ;
        });
  }

}
